package com.lll.handler;

import com.lll.config.Config;
import com.lll.constants.ProtocolConstants;
import com.lll.protocol.LoginRequestMessage;
import com.lll.protocol.LoginResponseMessage;
import com.lll.protocol.Message;
import com.lll.protocol.MessageHeader;
import com.lll.serialization.Serialization;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
@ChannelHandler.Sharable
/**
 * 必须和 LengthFieldBasedFrameDecoder 一起使用，确保接到的 ByteBuf 消息是完整的
 */
public class MessageCodecSharable extends MessageToMessageCodec<ByteBuf, Message> {
    @Override
    public void encode(ChannelHandlerContext ctx, Message msg, List<Object> outList) throws Exception {
        ByteBuf out = ctx.alloc().buffer();
        // 1. 1 字节的魔数
        out.writeByte(ProtocolConstants.MAGIC_NUMBER);
        // 2. 1 字节的版本,
        out.writeByte(1);
        // 3. 1 字节的序列化方式 jdk 0 , json 1
        out.writeByte(msg.getHeader().getSerializationType());
        // 4. 1 字节的指令类型
        out.writeByte(msg.getHeader().getType());
        // 5. 8 个字节
        out.writeLong(msg.getHeader().getSequenceId());
        // 6. 获取内容的字节数组
        byte[] bytes = Config.getSerializerAlgorithm(msg.getHeader().getSerializationType()).serialize(msg.getBody());
        // 7. 长度
        out.writeInt(bytes.length);
        // 8. 写入内容
        out.writeBytes(bytes);
        outList.add(out);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        byte magicNum = in.readByte();
        byte version = in.readByte();
        byte serializerAlgorithm = in.readByte(); // 0 或 1
        byte messageType = in.readByte(); // 0,1,2...
        long sequenceId = in.readLong();
        int length = in.readInt();
        byte[] bytes = new byte[length];
        in.readBytes(bytes);

        MessageHeader header = new MessageHeader(magicNum, version, serializerAlgorithm, messageType, sequenceId, length);

        // 找到反序列化算法
        Serialization.Algorithm algorithm = Config.getSerializerAlgorithm(serializerAlgorithm);
        // 确定具体消息类型
        if (messageType == Message.LoginRequestMessage) {
            Message<LoginRequestMessage> message = new Message<>();
            message.setHeader(header);

            LoginRequestMessage messageObj = algorithm.deserialize(LoginRequestMessage.class, bytes);
            message.setBody(messageObj);
            log.debug("{}", message);
            out.add(message);
        } else if (messageType == Message.LoginResponseMessage) {
            Message<LoginResponseMessage> message = new Message<>();
            message.setHeader(header);

            LoginResponseMessage messageObj = algorithm.deserialize(LoginResponseMessage.class, bytes);
            message.setBody(messageObj);
            log.debug("{}", message);
            out.add(message);
        }
        log.debug("{}, {}, {}, {}, {}, {}", magicNum, version, serializerAlgorithm, messageType, sequenceId, length);

    }

}
